import { Assets, Bounds, Container, Point, updateRenderGroupTransforms } from "pixi.js";
import { PixijsRender } from "../PixijsRender";
import { BaseEntity } from "./BaseEntity";
import { ViewState } from "./PixijsEntities";
let __point = new Point();
export class GroupEntity extends BaseEntity {
    allowChildSelection: boolean;

    constructor(pixiRender: PixijsRender) {
        super(pixiRender);
        this.view = new Container();
        this.name = 'group';
        //this.__render.viewRoot.addChild(this.view);
        this.allowChildSelection = false;
        this.className = this.constructor.name
        this.anchor = {x: 0.5, y: 0.5}
    }

    __getGlobalBounds() {
        let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;

        const updateBounds = (entity: BaseEntity, parentTransform = { x: 0, y: 0, rotation: 0, scaleX: 1, scaleY: 1 }) => {
            const { x, y, rotation, scaleX, scaleY } = parentTransform;

            // 计算当前实体的变换
            const entityX = x + entity.position.x * scaleX;
            const entityY = y + entity.position.y * scaleY;
            const entityRotation = rotation + entity.rotation;
            const entityScaleX = scaleX * entity.scale.x;
            const entityScaleY = scaleY * entity.scale.y;

            // 获取实体的宽高
            const width = entityScaleX * (entity.view?.width || 0);
            const height = entityScaleY * (entity.view?.height || 0);

            // 计算旋转后的四个顶点
            const corners = [
                { x: entityX, y: entityY },
                { x: entityX + width, y: entityY },
                { x: entityX, y: entityY + height },
                { x: entityX + width, y: entityY + height }
            ].map(corner => {
                const cos = Math.cos(entityRotation);
                const sin = Math.sin(entityRotation);
                const dx = corner.x - entityX;
                const dy = corner.y - entityY;
                return {
                    x: entityX + dx * cos - dy * sin,
                    y: entityY + dx * sin + dy * cos
                };
            });

            // 更新边界
            corners.forEach(corner => {
                minX = Math.min(minX, corner.x);
                minY = Math.min(minY, corner.y);
                maxX = Math.max(maxX, corner.x);
                maxY = Math.max(maxY, corner.y);
            });

            // 递归处理子节点
            entity.children.forEach(child => updateBounds(child, { x: entityX, y: entityY, rotation: entityRotation, scaleX: entityScaleX, scaleY: entityScaleY }));
        };

        updateBounds(this);

        return new Bounds(minX, minY, maxX, maxY);
    }

    fixBound() {
        let previousTransforms: { [key: string]: any } = {}
        this.children.forEach(e => {
            __point.set(e.position.x, e.position.y)
            const posGlobal = this.view.toGlobal(__point)
            previousTransforms[e.id] = {x: posGlobal.x, y: posGlobal.y};
        })
       
        let bounds = this.view.getLocalBounds();
       
        let pos = this.view.toGlobal({
            x: (bounds.minX + bounds.maxX) * 0.5,
            y: (bounds.minY + bounds.maxY) * 0.5,
        })
        pos = this.view.parent.toLocal(pos);
        this.position.x = pos.x;
        this.position.y = pos.y;
        this.view.position.x = pos.x;
        this.view.position.y = pos.y;
        
        this.children.forEach(e => {
            let posGlobal = previousTransforms[e.id];
            let local = this.view.toLocal(posGlobal);
            e.position.x = local.x;
            e.position.y = local.y;

            e.view.position.x = local.x;
            e.view.position.y = local.y;
        });
        updateRenderGroupTransforms(this.__render.app.stage.renderGroup, true);
    }

    move(dx: number, dy: number) {
        for (let child of this.children) {
            child.position.x += dx;
            child.position.y += dy;
        }
    }

    loadAssets() {
        if(!this.url || this.url ==='') {
            this.__render.world.update(this, "viewState", ViewState.Showing);
            return
        }
        console.log('loadAssets')
        this.__render.world.update(this, "viewState", ViewState.Loading);
        this.isPrefab = true;
        this.expanded = false;
        Assets.load(this.url).then((jsonData) => {
            if (this.viewState === ViewState.Loading) {
                this.__render.world.addBlockFromJson(jsonData, this);
                this.__render.world.update(this, "viewState", ViewState.Showing);
            }
            this.__render.viewDirty = true;
        });

    }
}